package com.bsj.travel.service.impl;

import com.bsj.travel.cached.redis.RedisCached;
import com.bsj.travel.config.constant.CaptchaConstant;
import com.bsj.travel.constant.Constants;
import com.bsj.travel.def.global.JsonResult;
import com.bsj.travel.def.global.JsonResultEnum;
import com.bsj.travel.exception.ApiException;
import com.bsj.travel.service.ValidateCodeService;
import com.bsj.travel.util.sign.Base64;
import com.bsj.travel.util.uuid.IdUtils;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * @author yinhao
 * @version 1.0
 * @description
 * @date 2022/9/14
 */
@Service
@RefreshScope
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private CaptchaConstant captchaConstant;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCached redisCached;

    /**
     * 创建图像验证码
     *
     * @return
     * @throws Exception
     */
    @Override
    public JsonResult createCaptcha() throws IOException, ApiException {
        String capStr = null, code = null;
        BufferedImage image = null;
        String type = captchaConstant.getType();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        // 生成验证码
        if ("math".equals(type)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(type)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        //设置验证码的过期时间 5分钟
        redisCached.set(verifyKey, code, 5 * 60);
        System.out.println("验证码：" + code + "\tuuid：" + uuid);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);
        return JsonResult.success(JsonResultEnum.SUCCESS, Map.of("uuid", uuid, "img", Base64.encode(os.toByteArray())));
    }

    /**
     * 校验验证码的正确性
     *
     * @param code
     * @param uuid
     * @throws Exception
     */
    @Override
    public void checkCaptcha(String code, String uuid) throws ApiException {
        if (StringUtils.isEmpty(code)) {
            throw new ApiException(JsonResultEnum.CAPTCHA_NULL_ERROR);
        }
        if (StringUtils.isEmpty(uuid)) {
            throw new ApiException(JsonResultEnum.CAPTCHA_INVALID);
        }
        String key = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCached.get(key);
        if (StringUtils.isEmpty(captcha)) {
            throw new ApiException(JsonResultEnum.CAPTCHA_INVALID);
        }
        //验证码只能使用一次
        redisCached.del(key);
        if (!code.equalsIgnoreCase(captcha)) {
            throw new ApiException(JsonResultEnum.CAPTCHA_ERROR);
        }
    }
}
